import express  from 'express';
import util from 'utility'

const router = express.Router();  

router.post('/add',async(req,res)=>{
        console.log(req.body);
        const postData = req.body;

        const user = req.user.user;
        const count = await req.prisma.Order.count({
            where:{
                createdAt:{
                    gte: new Date(util.YYYYMMDDHHmmss())
                }
            }
        });
        const OrderNum = util.YYYYMMDD('')+util.randomString(4,'ABCDEFG0123456789')+ `${count}`.padStart(5,'0');
        
       const order =  await req.prisma.Order.create({
            data:{
                OrderNum,
                uid: user.uid,
                fee: postData.fee,
                startName: postData.startLocationInfo.name,
                startLocation: postData.startLocationInfo.location,
                endName: postData.endLocationInfo.name,
                startLocation: postData.startLocationInfo.location,
                endLocation: postData.endLocationInfo.location,
                distance: postData.distance,
                OrderCarTypes:{
                    create: postData.carTypes.map(item=>({ 
                        carType: item.name ==="快车"?'fast':'zhuan',
                        fee: item.fee
                    }))
                }
            }
        })

        res.success(order)
})

router.get('/detail/:id',async (req,res)=>{

    const { id } = req.params;

    const order = await req.prisma.Order.findUnique({
        where: {
            id: Number(id)
        },
        include:{
            OrderCarTypes: true,
            passenger: true
        }
    })

    res.success(order);

})

router.post('/cancel',async(req,res)=>{
    const { id } = req.body;

    // 需要确保处于等待接单或者是司机未到达的状态
    const order = await req.prisma.Order.findUnique({
        where:{
            id,
            status:{
                in:['ordering', 'willArrive', 'arrived']
            }
        },
      
    })
    if(!order) return res.fail('订单不能被取消');
    await req.prisma.Order.update({
        where:{
            id
        },
        data:{
            status: 'passengerCancel'
        }
    })

    res.success('取消成功')

})

router.post('/getMyOrder', async (req,res)=>{
    console.log('请求的结果1')
    const { page = 1,limit=20, type = 'all' } = req.body;
    const uid = req.user.user.id;
    const where = {}
    if(type=='fast') where.carType = 'fast'
    if(type=='zhuan') where.carType = 'zhuan'

    const count = await req.prisma.Order.count({
        where:{
            uid,
            ...where
        }
    })

    const list = await req.prisma.Order.findMany({
        where:{
            uid,
            ...where
        },
        orderBy: {
            id: 'desc',
        },
        take: Number(limit),
        skip: (page-1)*limit
    })
    res.success({
        list,
        count
    })

})
// 已经接到客户
router.post('/getClient', async (req,res)=>{
    const { id } = req.body;
    await req.prisma.Order.update({
        where:{
            id
        },
        data:{
            status: 'arrived'
        }

    })
    const orderInfo = await req.prisma.Order.findUnique({
        where:{
            id: Number(id)
        },
        include:{
            OrderCarTypes: true,
            passenger: true
        }
    })

    if(orderInfo){
            //  socket通知客户 已经到达
            //   ClintMap.set(`${phone}_${type}`, ws);
            const client = req.ClintMap.get(`${orderInfo.passenger.phone}_passenger`)
            if(client) {
                client.send(JSON.stringify({
                    type:'driverArrive',
                }))
            }
        res.success('ok')
    }



})

router.post('/start', async (req,res)=>{
    const { id } = req.body;
    await req.prisma.Order.update({
        where:{
            id
        },
        data:{
            status: 'driving'
        }

    })
    const orderInfo = await req.prisma.Order.findUnique({
        where:{
            id: Number(id)
        },
        include:{
            OrderCarTypes: true,
            passenger: true
        }
    })

    if(orderInfo){
            //  socket通知客户 已经到达
            //   ClintMap.set(`${phone}_${type}`, ws);
            const client = req.ClintMap.get(`${orderInfo.passenger.phone}_passenger`)
            if(client) {
                client.send(JSON.stringify({
                    type:'driving',
                    payload:{
                        orderid:  Number(id)
                    }
                }))
            }
        res.success('ok')
    }



})

router.post('/complete', async (req,res)=>{
    const { id } = req.body;
    await req.prisma.Order.update({
        where:{
            id
        },
        data:{
            status: 'nopay'
        }

    })
    const orderInfo = await req.prisma.Order.findUnique({
        where:{
            id: Number(id)
        },
        include:{
            OrderCarTypes: true,
            passenger: true
        }
    })

    if(orderInfo){
            //  socket通知客户 完成订单了
            //   ClintMap.set(`${phone}_${type}`, ws);
            const client = req.ClintMap.get(`${orderInfo.passenger.phone}_passenger`)
            if(client) {
                client.send(JSON.stringify({
                    type:'complete',
                    payload:{
                        orderid:  Number(id)
                    }
                }))
            }
        res.success('ok')
    }



})

router.post('/pay', async (req,res)=>{
    const { id } = req.body;
    await req.prisma.Order.update({
        where:{
            id
        },
        data:{
            status: 'pay'
        }

    })
    res.success('ok')
})

export default  router;

